<template>
  <div class="main">
    <p class="main_text">原材料库存</p>
    <!-- ############################################## 查询 ############################################## -->
    <div class="top mb20 p20">
      <el-form :model="searchData">
        <div class="df">
          <el-form-item v-if="cmopany == 0" label="公司名称：" class="mr20" style="width: 20%;">
            <el-select v-model="searchData.companyNode" filterable placeholder="公司名称">
              <el-option v-for="item in companyList" :key="item.id" :label="item.companyName" :value="item.node" />
            </el-select>
          </el-form-item>
          <el-form-item label="原材料类型：" class="mr20" style="width: 20%;">
            <el-select v-model="searchData.rawMaterialType" placeholder="原材料类型：">
              <el-option v-for="item in materialTypeList" :key="item.type_id" :label="item.type_name"
                :value="item.type_id" />
            </el-select>
          </el-form-item>
          <el-form-item label="仓库名称：" style="width: 20%;" class="mr20">
            <el-select v-model="searchData.storeId" filterable placeholder="仓库名称：">
              <el-option v-for="item in WarehouseList" :key="item.warehouseId" :label="item.warehouseName"
                :value="item.warehouseId" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchTopForm">查询</el-button>
            <el-button type="primary" plain @click="resc">重置</el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <!-- ############################################## 表单 ############################################## -->
    <div class="cyr-flex">
      <div class="mb20">
        <el-button type="primary" @click="inboundBtn" v-if="roleList.write">入库</el-button>
        <el-button type="primary" plain @click="exportExcel" v-if="roleList.write">导出数据</el-button>
      </div>
      <div class="cyr-flex-box">
      <el-table @selection-change="handleSelectionChange" :data="tableData"
        :header-cell-style="{ background: '#f0f6fe' }" :show-overflow-tooltip="true" v-adaptive border>
        <el-table-column type="selection" width="50" />
        <el-table-column prop="id" label="原材料编号" :show-overflow-tooltip="true" />
        <el-table-column prop="type_name" label="原材料类型" :show-overflow-tooltip="true" min-width="100">
          <template #default="props">
            <el-text tag='span' style='cursor: pointer;' @click="details(props.row)">{{ props.row.type_name }}</el-text>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="price" label="定价" :show-overflow-tooltip="true" /> -->
        <!-- <el-table-column prop="rawMaterialType" label="原材料类型id" :show-overflow-tooltip="true" /> -->
        <!-- <el-table-column prop="storageLocation" label="仓储位置" :show-overflow-tooltip="true" /> -->
        <el-table-column prop="materialNum" label="仓储数量(kg)" :show-overflow-tooltip="true" />
        <el-table-column prop="warehouseName" label="仓库名称" :show-overflow-tooltip="true" />
        <el-table-column prop="created" label="创建时间" :show-overflow-tooltip="true" />
        <el-table-column prop="updated" label="更新时间" :show-overflow-tooltip="true" />
        <el-table-column fixed="right" label="操作" width="140">
          <template #default="props">
            <el-button size="small" link type="primary" @click="details(props.row)" v-if='roleList.read'>库存</el-button>
            <el-button size="small" link type="primary" @click="outBoundDiag(props.row)"
              v-if='roleList.write'>出库</el-button>
            <el-button size="small" link type="primary" @click="transferDiag(props.row)"
              v-if='roleList.write'>调拨</el-button>
          </template>
        </el-table-column>
      </el-table>
      <smartPager v-model:current-page="currentPage" v-model:page-size="pageSize" :total="Number(total)"
        @change="handleCurrentChange" />
      </div>
    </div>
    <!-- ############################################## 蒙层 ############################################## -->
    <!-- ****************************** 编辑原材料-----详情 ****************************** -->
    <el-drawer v-model="drawer" size="50%" style="background: #f5f9ff;">
      <div class="drawer_top p20">
        <h1 style="font-weight: 700; font-size: 1.125rem; color: #3d3d3d;">
          {{ editformData.type_name }}
        </h1>
        <span style="color: #9e9e9e; font-size: 0.75rem;">原材料编号：{{ editformData.id }}</span>
        <el-divider style="margin: 0.625rem 0;" />
        <el-form :model="editformData" label-width="8rem" label-position="left" class="df fww">
          <el-form-item style="width: 50%;" class="df ais">
            <template #label>
              <div class="df aic">
                <el-icon color="#9e9e9e" class="mr6">
                  <User />
                </el-icon>
                <p style="color: #9e9e9e;">原材料编号：</p>
              </div>
            </template>
            <el-text>{{ editformData.id }}</el-text>
          </el-form-item>
          <el-form-item style="width: 50%;" class="df ais">
            <template #label>
              <div class="df aic">
                <el-icon color="#9e9e9e" class="mr6">
                  <User />
                </el-icon>
                <p style="color: #9e9e9e;">原材料名称：</p>
              </div>
            </template>
            <el-text>{{ editformData.type_name }}</el-text>
          </el-form-item>
          <el-form-item style="width: 50%;" class="df ais">
            <template #label>
              <div class="df aic">
                <el-icon color="#9e9e9e" class="mr6">
                  <User />
                </el-icon>
                <p style="color: #9e9e9e;">仓库名称：</p>
              </div>
            </template>
            <el-text>{{ editformData.warehouseName }}</el-text>
          </el-form-item>
          <!-- <el-form-item style="width: 50%;" class="df ais">
                        <template #label>
                            <div class="df aic">
                                <el-icon color="#9e9e9e" class="mr6">
                                    <User />
                                </el-icon>
                                <p style="color: #9e9e9e;">仓库编码：</p>
                            </div>
                        </template>
                        <el-text>{{ editformData.storeId }}</el-text>
                    </el-form-item> -->
          <el-form-item style="width: 50%;" class="df ais">
            <template #label>
              <div class="df aic">
                <el-icon color="#9e9e9e" class="mr6">
                  <User />
                </el-icon>
                <p style="color: #9e9e9e;">单位：</p>
              </div>
            </template>
            <el-text>千克</el-text>
          </el-form-item>
          <el-form-item style="width: 50%;" class="df ais">
            <template #label>
              <div class="df aic">
                <el-icon color="#9e9e9e" class="mr6">
                  <User />
                </el-icon>
                <p style="color: #9e9e9e;">创建时间：</p>
              </div>
            </template>
            <el-text>{{ editformData.createdAt }}</el-text>
          </el-form-item>
          <el-form-item style="width: 50%;" class="df ais">
            <template #label>
              <div class="df aic">
                <el-icon color="#9e9e9e" class="mr6">
                  <User />
                </el-icon>
                <p style="color: #9e9e9e;">库存数量(kg)：</p>
              </div>
            </template>
            <el-text type="primary">{{ editformData.materialNum }}</el-text>
          </el-form-item>
          <el-form-item style="width: 50%;" class="df ais">
            <template #label>
              <div class="df aic">
                <el-icon color="#9e9e9e" class="mr6">
                  <User />
                </el-icon>
                <p style="color: #9e9e9e;">低储：</p>
              </div>
            </template>
            <el-input-number v-model="minStock" :step="1" step-strictly style="width: 80%;" :disabled="flag" />
          </el-form-item>
          <el-form-item style="width: 50%;" class="df ais">
            <template #label>
              <div class="df aic">
                <el-icon color="#9e9e9e" class="mr6">
                  <User />
                </el-icon>
                <p style="color: #9e9e9e;">高储：</p>
              </div>
            </template>
            <el-input-number v-model="maxStock" :step="1" step-strictly style="width: 80%;" :disabled="flag" />
          </el-form-item>
        </el-form>
        <div class="df jcc">
          <div>
            <el-button type="primary" size="small" @click="editDetails" v-if="roleList.write">修改</el-button>
            <el-button type="primary" size="small" plain @click="saveDetails">保存</el-button>
          </div>
        </div>
      </div>
      <div class="drawer_top p20 mt20">
        <div class="df aic jcc">原材料统计明细</div>
        <!-- <div class=" df jcsb">
                    <div class="mr10">
                        <el-select v-model="select" placeholder="明细类型" style="width: 7.1875rem">
                            <el-option label="Restaurant" value="1" />
                            <el-option label="Order No." value="2" />
                            <el-option label="Tel" value="3" />
                        </el-select>
                    </div>
                    <div style="width: 50%;" class="df aic b0 mr10">
                        <el-select v-model="select" placeholder="明细类型" style="width: 30%;">
                            <el-option label="Restaurant" value="1" />
                            <el-option label="Order No." value="2" />
                            <el-option label="Tel" value="3" />
                        </el-select>
                        <el-date-picker v-model="timeValue" type="datetimerange" range-separator="To"
                            start-placeholder="Start date" end-placeholder="End date" />
                    </div>
                    <div class="DocumentNumber">
                        <el-input v-model="input" placeholder="Please input" class="input-with-select">
                            <template #prepend>
                                <el-select v-model="select" placeholder="单据编号"
                                    style="width: 6.25rem;background-color: #fff;">
                                    <el-option label="Restaurant" value="1" />
                                    <el-option label="Order No." value="2" />
                                    <el-option label="Tel" value="3" />
                                </el-select>
                            </template>
                            <template #append>
                                <el-button :icon="Search"></el-button>
                            </template>
                        </el-input>
                    </div>
                </div> -->
        <el-table :data="tableDataDetial" style="width: 100%;" class="mt20"
          :header-cell-style="{ background: '#f5f7fa' }" border max-height="240">
          <el-table-column label="操作时间" prop="createdAt" :show-overflow-tooltip="true" />
          <el-table-column label="原材料名称" prop="rawMaterialName" :show-overflow-tooltip="true" />
          <!-- <el-table-column label="仓库编号" prop="storeId" :show-overflow-tooltip="true" /> -->
          <el-table-column label="仓储位置" prop="warehouseArea.adress" :show-overflow-tooltip="true" />
          <el-table-column label="库存数量(kg)" prop="num" :show-overflow-tooltip="true" />
          <!-- <el-table-column label="供应商" prop="supplierId" :show-overflow-tooltip="true" /> -->
          <!-- <el-table-column label="操作" prop="rawMaterialDescription" :show-overflow-tooltip="true" /> -->
          <!-- <el-table-column fixed="right" label="操作" width="130" v-if="editformData.type_name == '其他'">
                        <template #default="props">
                            <el-button size="small" link type="primary">出库</el-button>
                            <el-button size="small" link type="primary">调拨</el-button>
                        </template>
                    </el-table-column> -->
        </el-table>
      </div>
    </el-drawer>
    <!-- ****************************** 原材料入库 ****************************** -->
    <el-dialog v-model="InDialogVisible" width="40%" align-center @close="closeInDialogVisible">
      <template #header>
        <div class="df aic">
          <el-icon style="color: #fff;" size="20">
            <Edit />
          </el-icon>&nbsp;
          <p style="color: #fff;">原材料入库</p>
        </div>
      </template>
      <el-form :model="outData" ref="outDataModel" :rules="outDataModel_rules" label-position="top" class="df fww jcsb"
        v-if="InDialogVisibleDis == true">
        <el-form-item label="入库方式：" style="width: 48%;" prop="status">
          <el-select v-model="outData.status" placeholder="原材料入库">
            <el-option label="采购入库" value="0" />
            <!-- <el-option label="调拨入库" value="1" /> -->
            <el-option label="手动录入" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="原材料类型：" style="width: 48%;" prop="rawMaterialTypeName">
          <el-select v-model="outData.rawMaterialTypeName" placeholder="原材料类型：" filterable allow-create
            default-first-option>
            <el-option v-for="item in materialTypeList" :key="item.type_name" :label="item.type_name"
              :value="item.type_name" />
          </el-select>
        </el-form-item>
        <el-form-item label="原材料名称：" style="width: 48%;" prop="rawMaterialName">
          <el-input v-model="outData.rawMaterialName" placeholder="原材料名称" />
        </el-form-item>
        <el-form-item label="入库仓库：" style="width: 48%;" prop="storeId">
          <el-select v-model="outData.storeId" placeholder="入库仓库" @change="changeSearch">
            <el-option v-for="item in WarehouseList" :key="item.warehouseId" :label="item.warehouseName"
              :value="item.warehouseId" />
          </el-select>
        </el-form-item>
        <el-form-item label="存储位置：" style="width: 48%;" prop="storageLocation">
          <el-cascader style="width: 100%;" v-model="outData.storageLocation" placeholder="存储位置" :options="options"
            filterable @focus="changeArea" />
        </el-form-item>
        <el-form-item label="入库数量(kg)：" style="width: 48%;" prop="num">
          <el-input v-model.number="outData.num" placeholder="数量" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" plain @click="InDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="AddPutIn(outDataModel)" :loading="loading">
            入库
          </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- ****************************** 原材料新出库 ****************************** -->
    <el-dialog v-model="newStartcenterDialogVisible" width="40%" align-center>
      <template #header>
        <div class="df aic">
          <el-icon style="color: #fff;" size="20">
            <Edit />
          </el-icon>&nbsp;
          <p style="color: #fff;">原材料出库</p>
        </div>
      </template>
      <el-form :model="lineOutboundData" ref="newStartcenterDialogVisibleRef" label-position="top" class="df fww jcsb">
        <el-form-item label="出库仓库：" style="width: 48%;">
          <el-input v-model="lineOutboundData.warehouseName" disabled />
        </el-form-item>
        <el-form-item label="原材料类型：" style="width: 48%;">
          <el-select v-model="lineOutboundData.productType" disabled>
            <el-option v-for="item in materialTypeList" :key="item.type_id" :label="item.type_name"
              :value="item.type_id" />
          </el-select>
        </el-form-item>
        <el-form-item label="库存数量：" style="width: 48%;">
          <el-input v-model="lineOutboundData.materialNum" disabled />
        </el-form-item>
        <el-form-item label="出库数量(kg)：" :rules="[
          { required: true, message: '输入出库数量' },
          { type: 'number', message: '出库数量必须是数字' },
        ]" style="width: 48%;" prop="num">
          <el-input v-model.number="lineOutboundData.num" placeholder="出库数量" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" plain @click="newStartcenterDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="NewOutbound(newStartcenterDialogVisibleRef)" :loading="loading">
            出库
          </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- ****************************** 原材料出库 ****************************** -->
    <el-dialog v-model="StartcenterDialogVisible" width="40%" align-center>
      <template #header>
        <div class="df aic">
          <el-icon style="color: #fff;" size="20">
            <Edit />
          </el-icon>&nbsp;
          <p style="color: #fff;">原材料出库</p>
        </div>
      </template>
      <el-form :model="putInData" label-position="top" class="df fww jcsb">
        <el-form-item label="出库类型：" style="width: 48%;">
          <el-select v-model="putInData.status" placeholder="出库类型">
            <el-option label="销售出库" value="0" />
            <!-- <el-option label="调拨出库" value="1" /> -->
            <!-- <el-option label="自用出库" value="2" /> -->
          </el-select>
        </el-form-item>
        <el-form-item label="仓库名称：" style="width: 48%;">
          <el-select v-model="putInData.warehouseId" placeholder="仓库名称">
            <el-option v-for="item in WarehouseList" :key="item.warehouseId" :label="item.warehouseName"
              :value="item.warehouseId" />
          </el-select>
        </el-form-item>
        <el-form-item label="原材料类型：" style="width: 48%;">
          <el-select v-model="putInData.productType" placeholder="原材料类型">
            <el-option v-for="item in materialTypeList" :key="item.type_id" :label="item.type_name"
              :value="item.type_id" />
          </el-select>
        </el-form-item>
        <el-form-item label="出库数量(kg)：" style="width: 48%;">
          <el-input v-model="putInData.num" placeholder="出库数量" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" plain @click="StartcenterDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="Outbound"> 出库 </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- ****************************** 原材料新调拨 ****************************** -->
    <el-dialog v-model="NewDiaoBoDialogVisible" width="40%" align-center @close="DiaoBoDialogVisibleClose">
      <template #header>
        <div class="df aic">
          <el-icon style="color: #fff;" size="20">
            <Edit />
          </el-icon>&nbsp;
          <p style="color: #fff;">原材料调拨</p>
        </div>
      </template>
      <el-form :model="NewtransferData" ref="NewtransferDataRef" :rules="NewtransferDataRules" label-position="top"
        class="df fww jcsb pr20 pl20">
        <el-form-item label="调出仓库：" style="width: 48%;">
          <el-input v-model="NewtransferData.warehouseName" placeholder="调出仓库：" disabled />
        </el-form-item>
        <el-form-item label="调拨商品：" style="width: 48%;">
          <el-select v-model="NewtransferData.productType" placeholder="请选择调拨商品" disabled>
            <el-option v-for="item in materialTypeList" :key="item.type_id" :label="item.type_name"
              :value="item.type_id" />
          </el-select>
        </el-form-item>
        <el-form-item label="库存数量：" style="width: 48%;">
          <el-input v-model="NewtransferData.materialNum" disabled />
        </el-form-item>
        <el-form-item label="调入仓库：" style="width: 48%;" prop="inWarehouseId">
          <el-select v-model="NewtransferData.inWarehouseId" placeholder="请选择调入仓库" @change="changeTranserData1">
            <el-option v-for="item in WarehouseList" :key="item.warehouseId" :label="item.warehouseName"
              :value="item.warehouseId" />
          </el-select>
        </el-form-item>
        <el-form-item label="调入区域：" style="width: 48%;" prop="transferInArea">
          <el-cascader style="width: 100%;" v-model="NewtransferData.transferInArea" placeholder="存储位置"
            :options="optionsTransfer" filterable @focus="changeTranserArea1" />
        </el-form-item>
        <el-form-item label="调拨数量(kg)：" style="width: 48%;" prop="num">
          <el-input v-model.number="NewtransferData.num" placeholder="请选择调拨数量" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" plain @click="NewDiaoBoDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="Newtransfer(NewtransferDataRef)" :loading="loading">
            调拨
          </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- ****************************** 原材料调拨 ****************************** -->
    <el-dialog v-model="DiaoBoDialogVisible" width="40%" align-center @close="DiaoBoDialogVisibleClose">
      <template #header>
        <div class="df aic">
          <el-icon style="color: #fff;" size="20">
            <Edit />
          </el-icon>&nbsp;
          <p style="color: #fff;">原材料调拨</p>
        </div>
      </template>
      <el-form :model="transferData" label-position="top" class="df fww jcsb pr20 pl20">
        <el-form-item label="调出仓库：" style="width: 48%;">
          <el-select v-model="transferData.outWarehouseId" placeholder="请选择调出仓库">
            <el-option v-for="item in WarehouseList" :key="item.warehouseId" :label="item.warehouseName"
              :value="item.warehouseId" />
          </el-select>
        </el-form-item>
        <el-form-item label="调入仓库：" style="width: 48%;">
          <el-select v-model="transferData.inWarehouseId" placeholder="请选择调入仓库" @change="changeTranserData">
            <el-option v-for="item in WarehouseList" :key="item.warehouseId" :label="item.warehouseName"
              :value="item.warehouseId" />
          </el-select>
        </el-form-item>
        <el-form-item label="调入区域：" style="width: 48%;">
          <el-cascader style="width: 100%;" v-model="transferData.transferInArea" placeholder="存储位置"
            :options="optionsTransfer" filterable @focus="changeTranserArea" />
        </el-form-item>
        <el-form-item label="调拨商品：" style="width: 48%;">
          <el-select v-model="transferData.productType" placeholder="请选择调拨商品">
            <el-option v-for="item in materialTypeList" :key="item.type_id" :label="item.type_name"
              :value="item.type_id" />
          </el-select>
        </el-form-item>
        <el-form-item label="调拨数量(kg)：" style="width: 48%;">
          <el-input v-model="transferData.num" placeholder="请选择调拨数量" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" plain @click="DiaoBoDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="transfer"> 调拨 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import { exportFile } from "@/utils/exportFile.js";
import {
  RequestRawMaterialSave,
  RequestInventoryWarnningSave,
  RequestCompanyList,
  RequestEmployeeGetFunctionAuthorize,
  RequestUpWarehouseAreaGetAreaInfo,
  RequestRawMaterialGetMaterialDetail,
  RequestInventoryWarnningGetWarningByStatisticId,
  RequestMaterialStatisticGetlistlimit,
  RequestRawMaterialGetMaterialType,
  RequestWarehouseList,
  RequestRawMaterialGetlistlimit,
  RequestRawMaterialMaterialOutbound,
  RequestTransferSave,
  RequestMaterialStatisticOutputExcel,
} from "@/api/path/index.js";
import { User, Search, Edit } from "@element-plus/icons-vue";
import { formatTime, formatTimeHan } from "@/filters/index";
import { ElMessage } from "element-plus";

const searchData = ref<any>({
  storeId: "",
  rawMaterialId: "",
  rawMaterialName: "",
  companyNode: "",
});
/*------------------------------------- 按钮权限 -------------------------------------*/

import useAuthorize from "@/hooks/authorize";
let roleList = useAuthorize()
const loading = ref<any>(false);
//import { useRouter } from "vue-router";
// const authorizeFlag = ref<any>();
// const btnAuthority = () => {
//   // console.log(' useRouter()', useRouter().currentRoute.value.meta.title);
//   RequestEmployeeGetFunctionAuthorize(
//     useRouter().currentRoute.value.meta.title
//   ).then((res: any) => {
//     // console.log(res.resultObj);
//     if (res.resultObj == "W") {
//       authorizeFlag.value = false;
//     } else {
//       authorizeFlag.value = true;
//     }
//   });
// };
// btnAuthority();
/*------------------------------------- 按钮权限 -------------------------------------*/
const StartcenterDialogVisible = ref<any>(false); //出库
const newStartcenterDialogVisible = ref<any>(false); //出库
const InDialogVisible = ref<any>(false); //入库
const DiaoBoDialogVisible = ref<any>(false); //调拨
const NewDiaoBoDialogVisible = ref<any>(false); //调拨
const minStock = ref<any>(0); //低储
const maxStock = ref<any>(0); //高储
const tableData = ref<any>([]);
/* 查看详情&修改 */
const editformData = ref<any>({});
const multipleSelection = ref<any>([]);
const handleSelectionChange = (val: any) => {
  multipleSelection.value = val;
};
const drawer = ref(false); //详情
const flag = ref<any>(true);
/* ************************ 获取仓库下拉数据 ************************ */
const WarehouseList = ref<any>([]);
const getWarehouseList = () => {
  RequestWarehouseList().then((res: any) => {
    WarehouseList.value = res.resultObj;
  });
};
/* ************************ 获取原材料下拉数据 ************************ */
const materialTypeList = ref<any>([]);
const getMaterialTypeList = () => {
  RequestRawMaterialGetMaterialType().then((res: any) => {
    console.log("res.resultObj", res.resultObj);
    materialTypeList.value = res.resultObj;
  });
};
getMaterialTypeList();
getWarehouseList();
/* ********************************************************************** 获取公司列表 ***********************************************************************/
const cmopany = JSON.parse(localStorage.getItem("roleInfo")!).company;
const companyList = ref<any>([]);
const getCompanyList = () => {
  if (JSON.parse(localStorage.getItem("roleInfo")!).company == 0) {
    RequestCompanyList().then((res: any) => {
      console.log(res.resultObj);
      companyList.value = res.resultObj;
    });
  }
};
getCompanyList();
/* ************************ 分页获取数据 ************************ */
const total = ref<any>(10);
const currentPage = ref(1);
const pageSize = ref(10);
const getData = () => {
  RequestMaterialStatisticGetlistlimit({
    page: currentPage.value,
    rows: pageSize.value,
    rawMaterialName: searchData.value.rawMaterialName,
    rawMaterialType: searchData.value.rawMaterialType,
    companyNode: searchData.value.companyNode,
    storeId: searchData.value.storeId,
  }).then((res: any) => {
    res.resultObj.data.forEach((item: any) => {
      item.created = formatTime(item.createdAt);
      item.updated = formatTime(item.updatedAt);
    });
    tableData.value = res.resultObj.data;
    total.value = res.resultObj.total;
    console.log(res.resultObj.data);
  });
};
/* ************************ 查询 ************************ */
const searchTopForm = () => {
  getData();
  // RequestMaterialStatisticGetlistlimit({
  //     page: currentPage.value,
  //     rows: pageSize.value,
  //     rawMaterialName: searchData.value.rawMaterialName,
  //     rawMaterialType: searchData.value.rawMaterialType,
  //     storeId: searchData.value.storeId,
  // }).then((res: any) => {
  //     res.resultObj.data.forEach((item: any) => {
  //         item.createdAt = formatTime(item.createdAt)
  //         item.updatedAt = formatTime(item.updatedAt)
  //     });
  //     tableData.value = res.resultObj.data
  //     total.value = res.resultObj.total
  //     console.log(res.resultObj.data);
  // })
};
/* ************************ 查询 ************************ */
const resc = () => {
  (searchData.value.rawMaterialName = ""),
    (searchData.value.rawMaterialType = ""),
    (searchData.value.storeId = ""),
    (searchData.value.companyNode = ""),
    currentPage.value = 1;
    getData();
};
getData();
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  getData();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  getData();
};
/* ************************ 详情 ************************ */
const idSta = ref<any>();
const tableDataDetial = ref<any>([]);
const details = (row: any) => {
  editformData.value = row;
  console.log(row);
  RequestInventoryWarnningGetWarningByStatisticId(0, row.id).then(
    (res: any) => {
      if (res.resultObj != null) {
        idSta.value = res.resultObj.id;
        minStock.value = res.resultObj.minStock;
        maxStock.value = res.resultObj.maxStock;
      }
    }
  );
  RequestRawMaterialGetMaterialDetail(row.id).then((res: any) => {
    res.resultObj.forEach((item: any) => {
      item.warehouseArea.adress =
        item.warehouseArea.area + item.warehouseArea.position;
    });
    tableDataDetial.value = res.resultObj;
    console.log(tableDataDetial.value);
  });
  drawer.value = true;
};
/* ************************ 修改详情 ************************ */
const editDetails = () => {
  flag.value = false;
};
/* ************************ 保存详情 ************************ */
const saveDetails = () => {
  flag.value = true;
  RequestInventoryWarnningSave({
    minStock: minStock.value,
    maxStock: maxStock.value,
    statisticId: editformData.value.id,
    id: idSta.value,
    contentType: 0,
  }).then((res: any) => {
    if (res.success == true) {
      ElMessage.success(res.msg);
      //其它处理代码
      getData();
    } else {
      ElMessage.error(res.msg);
    }
  });
};
/* ************************ 入库 ************************ */
const outData = ref<any>({
  rawMaterialDescription: "",
  num: null,
  storageLocation: "",
  price: "",
  rawMaterialName: "",
  rawMaterialTypeName: "",
  status: "",
  storeId: "",
  measuringUnit: "kg",
});
const options = ref<any>([]);
const changeSearch = (event: any) => {
  RequestUpWarehouseAreaGetAreaInfo(event).then((res: any) => {
    res.resultObj.forEach((item: any) => {
      console.log(item);
      item.label = item.area;
      item.value = item.area;
      item.children = item.list;
      item.list.forEach((val: any) => {
        val.label = val.position;
        val.value = val.id;
      });
    });
    options.value = res.resultObj;
    console.log(res.resultObj);
  });
};
const changeArea = () => {
  if (outData.value.storeId == "") {
    ElMessage.error("请先选择仓库");
  }
};
const outDataModel = ref();
const outDataModel_rules = reactive({
  status: [{ required: true, message: "请选择入库方式", trigger: "change" }],
  rawMaterialTypeName: [
    { required: true, message: "请输入原材料类型", trigger: "change" },
  ],
  rawMaterialName: [
    { required: true, message: "请输入原材料名称", trigger: "change" },
  ],
  storeId: [{ required: true, message: "请选择入库仓库", trigger: "change" }],
  storageLocation: [
    { required: true, message: "请选择存储位置", trigger: "change" },
  ],
  num: [
    { required: true, message: "请输入入库数量", trigger: "change" },
    { type: "number", message: "请输入正确的入库数量", trigger: "change" },
  ],
});
const InDialogVisibleDis = ref<any>(true);
const inboundBtn = () => {
  InDialogVisible.value = true;
  InDialogVisibleDis.value = true;
};
const closeInDialogVisible = () => {
  outData.value.status = "";
  outData.value.rawMaterialName = "";
  outData.value.rawMaterialTypeName = "";
  outData.value.storeId = "";
  outData.value.storageLocation = "";
  outData.value.num = "";
};
const AddPutIn = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      RequestRawMaterialSave({
        rawMaterialDescription: outData.value.rawMaterialDescription,
        num: outData.value.num,
        storageLocation: outData.value.storageLocation[1],
        price: outData.value.price,
        rawMaterialName: outData.value.rawMaterialName,
        rawMaterialTypeName: outData.value.rawMaterialTypeName,
        status: outData.value.status,
        storeId: outData.value.storeId,
        measuringUnit: "kg",
      }).then((res: any) => {
        if (res.success == true) {
          ElMessage.success(res.msg);
          InDialogVisible.value = false;
          InDialogVisibleDis.value = false;
          outData.value.rawMaterialDescription = "";
          outData.value.num = "";
          outData.value.storageLocation = [];
          outData.value.price = "";
          outData.value.rawMaterialName = "";
          outData.value.rawMaterialTypeName = "";
          outData.value.status = "";
          outData.value.storeId = "";
          //其它处理代码
          getMaterialTypeList();
          setTimeout(() => {
            loading.value = false;
          }, 100);
          getData();
        } else {
          ElMessage.error(res.msg);
        }
      });
    }
  });
};
/* ************************ 出库 ************************ */
const putInData = ref<any>({
  status: "",
  warehouseId: "",
  productType: "",
  num: 0,
  measuringUnit: "kg",
  remark: "",
});
const newStartcenterDialogVisibleRef = ref();
const lineOutboundData = ref<any>({});
const outBoundDiag = (e: any) => {
  newStartcenterDialogVisible.value = true;
  console.log(e);
  lineOutboundData.value = e;
  lineOutboundData.value.num = null;
  lineOutboundData.value.status = 0;
  lineOutboundData.value.warehouseId = lineOutboundData.value.storeId;
  lineOutboundData.value.measuringUnit = "kg";
  lineOutboundData.value.productType = e.materialType;
  lineOutboundData.value.remark = "";
};
const NewOutbound = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate((valid: any) => {
    if (valid) {
      console.log(lineOutboundData.value);
      loading.value = true;
      delete lineOutboundData.value.createdAt;
      delete lineOutboundData.value.updatedAt;
      RequestRawMaterialMaterialOutbound(lineOutboundData.value).then(
        (res: any) => {
          if (res.code == 0) {
            ElMessage.success(res.msg);
            newStartcenterDialogVisible.value = false;
            //其它处理代码
            setTimeout(() => {
              loading.value = false;
            }, 100);
            getData();
          } else {
            ElMessage.error(res.msg);
            setTimeout(() => {
              loading.value = false;
            }, 100);
            getData();
          }
        }
      );
    }
  });
};
const Outbound = () => {
  console.log(putInData.value);
  RequestRawMaterialMaterialOutbound(putInData.value).then((res: any) => {
    if (res.code == 0) {
      ElMessage.success(res.msg);
      StartcenterDialogVisible.value = false;
      //其它处理代码
      getData();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

/* ************************ 调拨 ************************ */
const NewtransferData = ref<any>({
  num: null,
  transferStatus: "",
  transferInArea: "",
  inWarehouseId: "",
  outWarehouseId: "",
  contentType: null,
});
const NewtransferDataRef = ref<any>();
const NewtransferDataRules = ref<any>({
  num: [
    { required: true, message: "请输入调拨数量", trigger: "change" },
    { type: "number", message: "请输入正确的调拨数量", trigger: "change" },
  ],
  transferInArea: [
    { required: true, message: "请选择调入区域", trigger: "change" },
  ],
  inWarehouseId: [
    { required: true, message: "请选择调入仓库", trigger: "change" },
  ],
});
const transferDiag = (e: any) => {
  console.log(e);
  NewtransferData.value = e;
  NewDiaoBoDialogVisible.value = true;
  NewtransferData.value.outWarehouseId = e.storeId;
  NewtransferData.value.inWarehouseId = "";
  NewtransferData.value.transferInArea = "";
  NewtransferData.value.transferStatus = "";
  NewtransferData.value.num = "";
  NewtransferData.value.contentType = 0;
  NewtransferData.value.productType = e.materialType;
};
const Newtransfer = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate((valid: any) => {
    if (valid) {
      NewtransferData.value.num = Number(NewtransferData.value.num);
      console.log(NewtransferData.value);
      delete NewtransferData.value.createdAt;
      delete NewtransferData.value.updatedAt;
      const bold = new Blob([JSON.stringify(NewtransferData.value)], {
        type: "application/json;charset=UTF-8",
      });
      const transfer = new FormData();
      transfer.append("transfer", bold);
      RequestTransferSave(transfer).then((res: any) => {
        loading.value = true;
        if (res.success == true) {
          ElMessage.success(res.msg);
          NewDiaoBoDialogVisible.value = false;
          setTimeout(() => {
            loading.value = false;
          }, 100);
          getData();
        } else {
          ElMessage.error(res.msg);
          setTimeout(() => {
            loading.value = false;
          }, 100);
          // getData()
        }
      });
    }
  });
};

const optionsTransfer = ref<any>([]);
const changeTranserData = (event: any) => {
  RequestUpWarehouseAreaGetAreaInfo(event).then((res: any) => {
    res.resultObj.forEach((item: any) => {
      console.log(item);
      item.label = item.area;
      item.value = item.area;
      item.children = item.list;
      item.list.forEach((val: any) => {
        val.label = val.position;
        val.value = val.id;
      });
    });
    optionsTransfer.value = res.resultObj;
  });
};
const changeTranserArea = () => {
  if (transferData.value.inWarehouseId == "") {
    ElMessage.error("请先选择仓库");
  }
};
const changeTranserData1 = (event: any) => {
  RequestUpWarehouseAreaGetAreaInfo(event).then((res: any) => {
    res.resultObj.forEach((item: any) => {
      console.log(item);
      item.label = item.area;
      item.value = item.area;
      item.children = item.list;
      item.list.forEach((val: any) => {
        val.label = val.position;
        val.value = val.id;
      });
    });
    optionsTransfer.value = res.resultObj;
  });
};
const changeTranserArea1 = () => {
  if (NewtransferData.value.inWarehouseId == "") {
    ElMessage.error("请先选择仓库");
  } else {
    NewtransferData.value.transferInArea =
      NewtransferData.value.transferInArea[1];
  }
};
const transferData = ref<any>({
  num: "",
  transferStatus: "",
  transferInArea: "",
  inWarehouseId: "",
  outWarehouseId: "",
  contentType: 0,
});
const transfer = () => {
  transferData.value.transferInArea = transferData.value.transferInArea[1];
  transferData.value.num = Number(transferData.value.num);
  console.log(transferData.value);
  const bold = new Blob([JSON.stringify(transferData.value)], {
    type: "application/json;charset=UTF-8",
  });
  const transfer = new FormData();
  transfer.append("transfer", bold);
  RequestTransferSave(transfer).then((res: any) => {
    if (res.code == 0) {
      ElMessage.success(res.msg);
      DiaoBoDialogVisible.value = false;
      getData();
    } else {
      ElMessage.error(res.msg);
    }
  });
};
const DiaoBoDialogVisibleClose = () => {
  transferData.value.num = "";
  transferData.value.transferStatus = "";
  transferData.value.transferInArea = "";
  transferData.value.inWarehouseId = "";
  transferData.value.outWarehouseId = "";
  transferData.value.productType = "";
};
const exportExcel = () => {
  let nowDate = formatTimeHan(new Date());
  RequestMaterialStatisticOutputExcel({
    page: 1,
    rows: 100000,
  }).then((res: any) => {
    if (res.type == "application/json") {
      ElMessage.error("暂无数据导出");
    } else {
      exportFile(res, `${nowDate}所有原材料数据报表`);
    }
  });
};
</script>

<style scoped lang="scss">
.main {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  .top {
    width: 100%;
    background-color: #fff;
  }

  .content {
    width: 100%;
    background-color: #fff;
  }
}

.icon_i {
  position: absolute;
  top: 0;
  bottom: 0;
  left: -6.875rem;
  right: 0;
  margin: auto 0;
}

.downLoad {
  line-height: 1rem;
  margin-left: 0.625rem;
  color: #116cf8;
}

.el-select {
  width: 100%;
}

.el-input-number {
  width: 100%;
}

.drawer_top {
  width: 100%;
  background-color: #fff;
  border-radius: 0.5rem;
}

/* 弹出框样式 */
::v-deep .el-overlay {
  .el-dialog__header {
    background-color: #116cf8;
    margin-right: 0;
  }

  .el-dialog__title {
    color: #fff;
  }

  // .el-icon svg {
  //     color: #fff;
  // }
}

::v-deep .el-drawer {
  .el-overlay .el-icon svg {
    color: red;
  }

  .el-drawer__header {
    margin-bottom: 0;
  }
}

::v-deep .b0 {
  .el-input__wrapper:nth-child(1) {
    border-radius: 0.25rem 0rem 0rem 0.25rem;
    position: relative;
    left: 0.0625rem;
  }

  .el-input__wrapper:nth-child(2) {
    border-radius: 0rem 0.25rem 0.25rem 0rem;
  }
}

.DocumentNumber {
  .el-button {
    background-color: #fff;
    border: 0.0625rem solid #dcdfe6;
    border-left: none;
  }
}
</style>
